package com.azdebugit.future.test;
import java.util.concurrent.*;

public class CallableDemo implements Callable<String> {
    private int begin;
    private int end;
    private int sum;
    public CallableDemo(int begin, int end) {
        super();
        this.begin = begin;
        this.end = end;
    }
    public String call() throws Exception {
//        for(int i=begin;i<=end;i++){
            for(int j=begin;j<=end;j++){
                sum+=j;
            }
//        }
        Thread.sleep(8000);
        return begin+"-" +end+"的和："+ sum;
    }
    public static void main(String[] args) throws Exception {
        CallableDemo callable = new CallableDemo(1,1000);
        CallableDemo callable2 = new CallableDemo(1,10);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 5, 5L, TimeUnit.SECONDS, new LinkedBlockingDeque());
        CompletionService csRef = new ExecutorCompletionService(executor);
        csRef.submit(callable);
        csRef.submit(callable2);
//CompletionService 的take()方法获取最先执行完的线程的Future对象。
        System.out.println(csRef.take().get());
        System.out.println(csRef.take().get());
    }
}